package org.niit.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object SparkStreaming_01 {

  def main(args: Array[String]): Unit = {
    //演示 用Spark Streaming  做实时单词统计分析
    //准备环境
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("spark")
    //初始化 SparkStreamingContext            采集周期为3秒
    val ssc = new StreamingContext(sparkConf, Seconds(3))
    ssc.sparkContext.setLogLevel("ERROR")

    //通过端口的监听创建 DStream
    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999) //nc localhost 9999
    // spark word word spark
    val words: DStream[String] = lines.flatMap(_.split(" "))
    //[spark,word,word,spark]
    val wordOne: DStream[(String, Int)] = words.map((_, 1))
    //（Spark ，1） （word,1）(word,1)(spark,1)
    val resDS: DStream[(String, Int)] = wordOne.reduceByKey(_ + _)
    //打印数据
    resDS.print()


    //开启采集器
    ssc.start()
    //等待采集器关闭
    ssc.awaitTermination()
  }
}
